package com.me.study.jdk8.stream;

import java.util.function.BinaryOperator;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * 三参 Reduce 并行、串行简单求和
 *
 * @author ME
 */
public class ReduceSum {

    public static void main(String[] args) {
        System.out.println("\nIntStream reduce 求和");
        IntStream stream = IntStream.of(1, 4, 7, 2, 9);
        System.out.println(stream.reduce(Integer::sum).getAsInt());

        System.out.println("\nIntStream reduce 求和");
        stream = IntStream.of(1, 4, 7, 2, 9);
        System.out.println(stream.reduce(0, Integer::sum));

        System.out.println("\n一参 Reduce 并行求和");
        Stream<Integer> stream1 = Stream.of(1, 4, 7, 2, 9);
        Integer result = stream1.parallel().reduce(Integer::sum).get();
        System.out.println(result);

        System.out.println("\n两参 Reduce 并行求和");
        stream1 = Stream.of(1, 4, 7, 2, 9);
        result = stream1.parallel().reduce(0, new BinaryOperator<Integer>() {
            @Override
            public Integer apply(Integer i1, Integer i2) {
                return i1 + i2;
            }
        });
        System.out.println(result);

        System.out.println("\n三参 Reduce 并行求和");
        stream1 = Stream.of(1, 4, 7, 2, 9);
        result = stream1.parallel().reduce(0,
                (s1, s2) -> s1 + s2,
                Integer::sum);
        System.out.println(result);

        System.out.println("\n三参 Reduce 非并行求和");
        stream1 = Stream.of(1, 4, 7, 2, 9);
        result = stream1.reduce(0,
                (s1, s2) -> s1 + s2,
                Integer::sum);
        System.out.println(result);
    }

}
